<?php
Yii::import('ext.common.RESTful.RESTful');
Yii::import('ext.common.RESTful.RESTController');
class PostController extends RESTController
{
	public $logModelClass = 'RestServerApiLog';
	public $autoLogRequest = true;

	public function checkAccess($user)
	{
		$user = Yii::app()->httpUser;

		if (!empty($user->id)) return false;
		return true;
	}

	/**
	 * @inheritdoc
	 */
	public function accessRules()
	{
		return array(
			array('deny',
		'actions' => array('index'),
		'expression'=>array($this, 'checkAccess'),
		),
		);
	}
	function init()
	{
		parent::init();

		Yii::app()->setComponent('user', Yii::app()->httpUser);
	}

	function filters()
	{
		return array('accessControl');
	}

	public function actionIndex()
	{
		if(isset($_POST))
		{
				#$kind_id=Yii::app()->request->getPost('kind_id');
				$kind_uk=Yii::app()->request->getPost('kind_uk');

				$real_id=Yii::app()->request->getPost('real_id');
				$name=Yii::app()->request->getPost('name');
				$created_by=Yii::app()->request->getPost('created_by');
				$comment=Yii::app()->request->getPost('comment');
				$value=Yii::app()->request->getPost('value');

				$kind=Kind::model()->findByAttributes(array('uk'=>$kind_uk));

				if(!$kind){
					$kindModel= new Kind();
					$kindModel->uk=$kind_uk;
					$kindModel->kind_name=$kind_uk;
					if($kindModel->save()){
						$kind_id=$kindModel->id;
					}
				}
				else
					$kind_id=$kind->id;

				$testItem=Item::model()->findByAttributes(array('kind_id'=>$kind_id,'real_id'=>$real_id));
				if(!$testItem){
					$item= new Item();
					$item->kind_id=$kind_id;
					$item->real_id=$real_id;
					$item->name=$name;

					if($item->save()){
						$item_id=$item->id;
					}
				}
				else{
					$item_id=$testItem->id;
				}

				$revision= new Revision();
				$revision->item_id=$item_id;
				$revision->created_by=$created_by;
				$revision->comment=$comment;
				$revision->value=json_encode($value);
				$revision->created_time= new CDbExpression('NOW()');
				$revision->save();
				echo 'done';
			}
	}

	protected  function getIP()
	{
		if($_SERVER['REMOTE_ADDR'] && isset($_SERVER['HTTP_CLIENT_IP']))
		{
			return $_SERVER['HTTP_CLIENT_IP'];
		}elseif($_SERVER['REMOTE_ADDR'])
		{
			return $_SERVER['REMOTE_ADDR'];
		}
		elseif($_SERVER['HTTP_CLIENT_IP'])
		{
			return $_SERVER['HTTP_CLIENT_IP'];
		}elseif($_SERVER['HTTP_X_FORWARDED_FOR'])
		{
			return $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
	}
	}
?>
